package com.haitaoit.chengquan.module.center.activity.xuqiu;

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.baiduservice.LocationService;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.model.MyXuqiuMapModel;
import com.haitaoit.chengquan.module.home.activity.maintenance.MaintenanceDetailActivity2;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyXuqiuMapActivity extends BaseActivity {
    //    @ViewInject(R.id.map_all)
//    TextView map_all;
//    @ViewInject(R.id.map_baojia)
//    TextView map_baojia;
//    @ViewInject(R.id.map_xinyu)
//    TextView map_xinyu;
    @ViewInject(R.id.bmapView)
    MapView mMapView;

    private List<MyXuqiuMapModel> new_list = new ArrayList<MyXuqiuMapModel>();
    private int mapIndex = -1;

    //    private int index = 0;

    private boolean isToast = true;
    private BaiduMap mBaiduMap;
    private LocationService locationService;
    private BDLocationListener mListener;
    private double latitude = 39.915174;
    private double longitude = 121.446496;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView_V(R.layout.activity_my_xuqiu_map);
        setTitle_V("报价供应商");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);

        id = getIntent().getStringExtra("id");

        mBaiduMap = mMapView.getMap();
        mListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (isToast) {
                    isToast = false;
                    if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                        MapStatusUpdate u1 = MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(11).build());
                        mBaiduMap.setMapStatus(u);
                        mBaiduMap.setMapStatus(u1);
                    }
                    if (!("").equals(location.getCity())) {
                        if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                            ToastUtils.showToast("定位成功");
                        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                            // 运营商信息
                            ToastUtils.showToast("网络定位成功");
                        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                            ToastUtils.showToast("定位成功");
                        } else if (location.getLocType() == BDLocation.TypeServerError) {
                            ToastUtils.showToast("定位失败,无法搜索到商家");
                        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                            ToastUtils.showToast("定位失败,无法搜索到商家,请检查网络是否通畅");
                        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                            ToastUtils.showToast("定位失败,无法搜索到商家");
                        }
                        ToastUtils.showToast("定位城市:" + location.getCity());

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        LatLng point = new LatLng(latitude, longitude);
                        // 构建Marker图标
                        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pic_tra);
                        // 构建MarkerOption，用于在地图上添加Marker
                        OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                        // 在地图上添加Marker，并显示
                        Marker marker = (Marker) mBaiduMap.addOverlay(option);
                        marker.setZIndex(Integer.MAX_VALUE);
                        httpGetdemand_map_list();//请求
                    }
                }
            }


        };
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
        Vibrator mVibrator = (Vibrator) this.getSystemService(Service.VIBRATOR_SERVICE);
        locationService.start();// 定位SDK

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                if (mapIndex == marker.getZIndex()) {
                    mBaiduMap.hideInfoWindow();
                    mapIndex = -1;
                } else {
                    mapIndex = marker.getZIndex();
                    LatLng point1 = marker.getPosition();
                    // 创建InfoWindow展示的view
                    View view = LayoutInflater.from(MyXuqiuMapActivity.this).inflate(R.layout.textview, null);
                    TextView button = (TextView) view.findViewById(R.id.text);
                    button.setBackgroundResource(R.color.map_color);
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!(marker.getZIndex() == Integer.MAX_VALUE)) {
                                Intent intent = new Intent();
                                intent.setClass(MyXuqiuMapActivity.this, MaintenanceDetailActivity2.class);
                                intent.putExtra("id", new_list.get(marker.getZIndex()).getId());
                                startActivity(intent);
                            }
                        }
                    });
                    if (marker.getZIndex() == Integer.MAX_VALUE) {
                        button.setText("我的位置");
                    } else {
                        button.setText(new_list.get(marker.getZIndex()).getName());
                    }
                    button.setGravity(Gravity.CENTER);
                    button.setTextSize(12);
                    button.setTextColor(Color.WHITE);
                    // 定义用于显示该InfoWindow的坐标点
                    // 创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
                    InfoWindow mInfoWindow = new InfoWindow(view, point1, -100);
                    // 显示InfoWindow
                    mBaiduMap.showInfoWindow(mInfoWindow);
                }
                return false;
            }
        });
    }

    @Override
    public void onResume() {
        locationService.start();// 定位SDK
        super.onResume();
    }

    @Override
    public void onPause() {
        locationService.stop();
        super.onPause();
    }

    private void httpGetdemand_map_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdemand_map_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<MyXuqiuMapModel>>() {
                                    }.getType());
                            for (int i = 0; i < new_list.size(); i++) {
                                LatLng point = new LatLng(Double.valueOf(new_list.get(i).getLatitude()),
                                        Double.valueOf(new_list.get(i).getLongitude()));
                                // 构建Marker图标
                                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.pic42);
                                // 构建MarkerOption，用于在地图上添加Marker
                                OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                                // 在地图上添加Marker，并显示
                                Marker marker = (Marker) mBaiduMap.addOverlay(option);
                                marker.setZIndex(i);
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /** @OnClick({R.id.map_all, R.id.map_baojia_LL, R.id.map_xinyu_LL,})
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.map_all:// 全部
    setColor();
    map_all.setTextColor(getResources().getColor(R.color.app_color));
    break;
    case R.id.map_baojia_LL:// 报价
    setColor();
    map_baojia.setTextColor(getResources().getColor(R.color.app_color));
    Drawable img = getResources().getDrawable(R.mipmap.img34_1);
    img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
    map_xinyu.setCompoundDrawables(null, null, img, null);
    if (index == 0) {    index = 1;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img33_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_baojia.setCompoundDrawables(null, null, nav_up, null);
    } else if (index == 1) {    index = 0;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img34_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_baojia.setCompoundDrawables(null, null, nav_up, null);
    } else {    index = 1;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img33_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_baojia.setCompoundDrawables(null, null, nav_up, null);    }    break;
    case R.id.map_xinyu_LL:// 信誉
    setColor();
    map_xinyu.setTextColor(getResources().getColor(R.color.app_color));
    Drawable img2 = getResources().getDrawable(R.mipmap.img34_1);
    img2.setBounds(0, 0, img2.getMinimumWidth(), img2.getMinimumHeight());
    map_baojia.setCompoundDrawables(null, null, img2, null);
    if (index == 2) {    index = 3;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img33_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_xinyu.setCompoundDrawables(null, null, nav_up, null);
    } else if (index == 3) {    index = 2;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img34_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_xinyu.setCompoundDrawables(null, null, nav_up, null);    } else {
    index = 3;
    Drawable nav_up = getResources().getDrawable(R.mipmap.img33_1);
    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
    map_xinyu.setCompoundDrawables(null, null, nav_up, null);    }    break;    }
    super.onClick(v);    }
    public void setColor() {
    map_all.setTextColor(getResources().getColor(R.color.black_text));
    map_baojia.setTextColor(getResources().getColor(R.color.black_text));
    map_xinyu.setTextColor(getResources().getColor(R.color.black_text));
    }*/
}